<template>
  <div class="lianjie-gongyi-page">
    <div class="table1_container">
      <div class="table1_dataShower" style="padding-bottom: 50px; padding-top: 50px; box-sizing: border-box">
        <button class="report-top-button" @click="back">返回上级页面</button>
        <button class="report-top-button" @click="openFieldDialog">选择字段</button>
        <button class="report-top-button" @click="printReport">报表打印</button>
        <div style="text-align: center; margin: 10px 0;">
          <div style="display: inline-flex; gap: 20px;">
            <div style="display: flex; align-items: center;">
              <div
                style="width: 16px; height: 16px; background-color: #ffffff; border: 1px solid #ddd; margin-right: 5px;"
              />
              <span>未完成</span>
            </div>
            <div style="display: flex; align-items: center;">
              <div
                style="width: 16px; height: 16px; background-color: #e6f7e6; border: 1px solid #ddd; margin-right: 5px;"
              />
              <span>已完成</span>
            </div>
            <div style="display: flex; align-items: center;">
              <div
                style="width: 16px; height: 16px; background-color: #ffebeb; border: 1px solid #ddd; margin-right: 5px;"
              />
              <span>不合格重采</span>
            </div>
          </div>
        </div>
        <h1>钢筋机械连接接头检验报告汇总表（工艺检）</h1>
        <div style="width:90%;margin:0 auto;display: flex">
          <div style="text-align: left">
            <span>工程名称:</span>
            <span>{{ projectName + '  ' + subprojectName }}</span>
          </div>
          <div style="margin-left: 50em;letter-spacing: 2em">
            <span>年月日</span>
          </div>
        </div>
        <table class="wendu-table1_top_table">
          <tr>
            <template v-for="field in visibleFields">
              <td
                v-if="field.type === 'group'"
                :key="'header-group-' + field.key"
                :colspan="fieldColspan(field)"
              >
                {{ field.label }}
              </td>
              <td
                v-else
                :key="'header-' + field.key"
                :rowspan="2"
                :colspan="field.colspan || 1"
              >
                {{ field.label }}
              </td>
            </template>
          </tr>
          <tr v-if="visibleGroupFields.length">
            <template v-for="field in visibleGroupFields">
              <template v-for="child in field.children">
                <td
                  v-if="child.columns && child.columns.length"
                  :key="'subheader-' + field.key + '-' + child.key"
                  :colspan="child.columns.length"
                >
                  {{ child.label }}
                </td>
              </template>
            </template>
          </tr>
          <tr v-for="(item, index) in reportData" :key="'row-' + index">
            <template v-for="field in visibleFields">
              <template v-if="field.type === 'group'">
                <template v-for="child in field.children">
                  <template v-for="(column, colIndex) in child.columns">
                    <td :key="field.key + '-' + child.key + '-' + index + '-' + colIndex">
                      {{ column.getValue(item, colIndex) }}
                    </td>
                  </template>
                </template>
              </template>
              <template v-else>
                <td
                  :key="field.key + '-' + index"
                  :colspan="field.colspan || 1"
                >
                  {{ getFieldDisplayValue(field, item) }}
                </td>
              </template>
            </template>
          </tr>
          <tr>
            <td :colspan="totalColumns" style="text-align: left">
              说明：在检验不合格后又重新取样检验合格的，两次检验结果都必须统计在汇总表中。
            </td>
          </tr>
        </table>
        <div style="text-align: left; width: 90%;margin: 0 auto;display: flex">
          <div>施工单位项目技术负责人：{{ 'XXX' }}</div>
          <div style="margin-left: 10%">总监理工程师(建设单位项目技术负责人)：{{ 'XXX' }}</div>
          <div style="margin-left: 10%">（监理项目部章）</div>
          <div style="margin-left: 10%">填表人：{{ 'XXX' }}</div>
        </div>
      </div>
    </div>
    <el-dialog
      title="选择显示字段"
      :visible.sync="fieldDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <div style="max-height: 500px; overflow-y: auto;">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          style="margin-bottom: 15px;"
        >
          全选
        </el-checkbox>
        <el-divider></el-divider>
        <el-checkbox-group v-model="selectedFields" @change="handleCheckedFieldsChange" class="field-checkbox-group">
          <div
            v-for="field in allFields"
            :key="field.key"
            style="margin-bottom: 10px;"
          >
            <el-checkbox :label="field.key">{{ field.label }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmFieldSelection">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMechinalTablePreview } from '@/api/statementManage/xianChang/xianChang'

export default {
  data() {
    return {
      localStorageId: '',
      reportData: [],
      projectName: '',
      subprojectName: '',
      fieldDialogVisible: false,
      checkAll: true,
      isIndeterminate: false,
      selectedFields: [],
      allFields: [
        { key: 'batch', label: '批次', colspan: 1, getValue: item => item.dataId },
        { key: 'steelType', label: '牌号', colspan: 1, getValue: item => item.steelType },
        { key: 'connectorLevel', label: '等级及接头', colspan: 1, getValue: item => item.connectorLevel },
        { key: 'representAmount', label: '代表数量（个）', colspan: 1, getValue: item => item.representAmount },
        { key: 'usePart', label: '使用部位', colspan: 1, getValue: item => item.usePart },
        { key: 'checkDate', label: '收样日期', colspan: 1, getValue: item => item.checkDate },
        { key: 'reportDate', label: '报告日期', colspan: 1, getValue: item => item.reportDate },
        { key: 'reportNumber', label: '试验报告编号', colspan: 1, getValue: item => item.reportNumber },
        { key: 'diameter', label: '直径或横截面尺寸(mm)', colspan: 1, getValue: item => item.diameter },
        { key: 'connectorArea', label: '横截面积 (mm2）', colspan: 1, getValue: item => item.connectorArea },
        {
          key: 'jointGroup',
          label: '接头试件',
          type: 'group',
          children: [
            {
              key: 'pullStrengths',
              label: '抗拉强度(MPa)',
              columns: [
                { getValue: item => item.pullStrengths && item.pullStrengths[0] },
                { getValue: item => item.pullStrengths && item.pullStrengths[1] },
                { getValue: item => item.pullStrengths && item.pullStrengths[2] }
              ]
            },
            {
              key: 'remainTransform',
              label: '残余变形',
              columns: [{ getValue: item => item.remainTransform }]
            },
            {
              key: 'breakPositionFeature',
              label: '断裂位置及特征',
              columns: [{ getValue: item => item.breakPositionFeature }]
            }
          ]
        },
        { key: 'conclusion', label: '结论', colspan: 1, getValue: item => item.conclusion },
        { key: 'projectName', label: '项目名称', colspan: 1, getValue: (item, vm) => vm.projectName },
        { key: 'subprojectName', label: '单位工程', colspan: 1, getValue: (item, vm) => vm.subprojectName },
        { key: 'primaryKey', label: '主键', colspan: 1, getValue: item => item.dataId },
        { key: 'checkMethod', label: '检验型式', colspan: 1, getValue: item => item.checkMethod },
        { key: 'connectorType', label: '接头类型', colspan: 1, getValue: item => item.connectorType },
        { key: 'yanshouRule', label: '验收规范', colspan: 1, getValue: item => item.yanshouRule },
        { key: 'projectNumber', label: '工程号', colspan: 1, getValue: item => item.projectNumber },
        { key: 'superviseNumber', label: '监督号', colspan: 1, getValue: item => item.superviseNumber },
        { key: 'checkCompany', label: '检测单位', colspan: 1, getValue: item => item.checkCompany },
        { key: 'delegateCompany', label: '委托单位', colspan: 1, getValue: item => item.delegateCompany },
        { key: 'delegateNumber', label: '委托编号', colspan: 1, getValue: item => item.delegateNumber },
        { key: 'witnessCompany', label: '见证单位', colspan: 1, getValue: item => item.witnessCompany },
        { key: 'witnessPerson', label: '见证人', colspan: 1, getValue: item => item.witnessPerson },
        { key: 'sendPerson', label: '送样人', colspan: 1, getValue: item => item.sendPerson },
        { key: 'checkType', label: '检验类别', colspan: 1, getValue: item => item.checkType },
        { key: 'jiansheCompany', label: '建设单位', colspan: 1, getValue: item => item.jiansheCompany },
        { key: 'shigongCompany', label: '施工单位', colspan: 1, getValue: item => item.shigongCompany }
      ]
    }
  },
  created() {
    this.selectedFields = this.allFields.map(field => field.key)
  },
  computed: {
    visibleFields() {
      return this.allFields.filter(field => this.selectedFields.includes(field.key))
    },
    visibleGroupFields() {
      return this.visibleFields.filter(field => field.type === 'group')
    },
    totalColumns() {
      return this.visibleFields.reduce((sum, field) => sum + this.fieldColspan(field), 0)
    }
  },
  async mounted() {
    const sessionData = sessionStorage.getItem('tempObj1')
    if (!sessionData) {
      return
    }
    const parseData = JSON.parse(sessionData)
    this.projectName = parseData.projectName
    this.subprojectName = parseData.subprojectName
    const subprojectId = parseData.subprojectId
    const { result } = await getMechinalTablePreview(subprojectId, '工艺检')
    this.reportData = result || []
  },
  beforeDestroy() {
    if (this.localStorageId) {
      localStorage.removeItem(this.localStorageId)
    }
    document.querySelector('body').setAttribute('style', 'background-color: white;')
  },
  beforeCreate() {
    document.querySelector('body').setAttribute('style', 'background-color:#f5f5f5;')
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    openFieldDialog() {
      this.fieldDialogVisible = true
    },
    handleCheckAllChange(val) {
      if (val) {
        this.selectedFields = this.allFields.map(f => f.key)
      } else {
        this.selectedFields = []
      }
      this.isIndeterminate = false
    },
    handleCheckedFieldsChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.allFields.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allFields.length
    },
    confirmFieldSelection() {
      if (this.selectedFields.length === 0) {
        this.$message.warning('请至少选择一个字段！')
        return
      }
      this.fieldDialogVisible = false
      this.handleCheckedFieldsChange(this.selectedFields)
      this.$message.success('字段选择已更新！')
    },
    fieldColspan(field) {
      if (field.type === 'group') {
        return field.children.reduce((sum, child) => sum + child.columns.length, 0)
      }
      return field.colspan || 1
    },
    getFieldDisplayValue(field, item) {
      if (typeof field.getValue === 'function') {
        return field.getValue(item, this) || ''
      }
      return item[field.key] || ''
    },
    printReport() {
      window.print()
    }
  }
}
</script>

<style>
.table1_container {
  width: 4500px;
  background: white;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding-bottom: 20px;
}

.table1_dataShower {
  width: 80%;
  background: white;
  margin: 0 auto;
  border: 2px black solid;
}

.report-top-button {
  display: block;
  margin: 0 auto;
  margin-bottom: 20px;
  padding: 12px 28px;
  font-size: 16px;
  font-weight: 600;
  font-family: 'Arial', sans-serif;
  color: #ffffff;
  background: linear-gradient(90deg, #1e3a8a, #3b82f6);
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.report-top-button:hover {
  background: linear-gradient(90deg, #1e3a8a, #2563eb);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.report-top-button:active {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  transform: translateY(0);
}

.wendu-table1_top_table {
  width: 90%;
  margin: 0 auto;
  border-collapse: collapse;
  border: 1px solid black;
  table-layout: fixed;
}

.wendu-table1_top_table tr td {
  height: 50px;
  border: 1px solid black;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.field-checkbox-group {
  text-align: left;
}

.field-checkbox-group .el-checkbox {
  width: 100%;
}

@media print {
  @page {
    size: A4 landscape;
    margin-left: 15mm;
    margin-right: 15mm;
  }
}
</style>

